/*
 * @lc app=leetcode id=114 lang=cpp
 *
 * [114] Flatten Binary Tree to Linked List
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        flat(root);
    }

    TreeNode *flat(TreeNode *root) {
        if(!root) {
            return NULL;
        }
        if (!root->left && !root->right) {
            return root;
        }

        TreeNode *tmpl = root->left;
        TreeNode *tmpr = root->right;

        TreeNode *tail = flat(tmpl);
        if (tmpl) {
            root->right = tmpl;
            tail->right = tmpr;
        } else {
            root->right = tmpr;
        }
        tail = flat(tmpr);

        return tail;
    }
};

